/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tmq.diancan.service.impl;

import com.tmq.diancan.dto.CartDTO;
import com.tmq.diancan.dto.DiancanOrderDetailDTO;
import com.tmq.diancan.entity.DiancanOrderDetail;
import com.tmq.diancan.entity.DiancanOrderMaster;
import com.tmq.diancan.entity.DiancanProductInfo;
import com.tmq.diancan.entity.OrderDetail;
import com.tmq.diancan.enums.OrderStatusEnum;
import com.tmq.diancan.enums.ResultEnum;
import com.tmq.diancan.exception.BladeRestExceptionTranslator;
import com.tmq.diancan.exception.ServiceException;
import com.tmq.diancan.service.IDiancanOrderMasterService;
import com.tmq.diancan.service.IDiancanProductInfoService;
import com.tmq.diancan.service.WebSocket;
import com.tmq.diancan.utils.UUIDUtil;
import com.tmq.diancan.vo.DiancanOrderDetailVO;
import com.tmq.diancan.mapper.DiancanOrderDetailMapper;
import com.tmq.diancan.service.IDiancanOrderDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.ehcache.util.ProductInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;
import sun.security.util.KeyUtil;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单商品 服务实现类
 *
 * @author tangmqb
 * @since 2020-03-21
 */
@Service
public class DiancanOrderDetailServiceImpl extends ServiceImpl<DiancanOrderDetailMapper, DiancanOrderDetail> implements IDiancanOrderDetailService {

	@Autowired
	IDiancanProductInfoService productService;
	@Autowired
	IDiancanOrderMasterService orderMasterService;

	@Autowired
	private WebSocket webSocket;

	@Override
	public IPage<DiancanOrderDetailVO> selectDiancanOrderDetailPage(IPage<DiancanOrderDetailVO> page, DiancanOrderDetailVO diancanOrderDetail) {
		return page.setRecords(baseMapper.selectDiancanOrderDetailPage(page, diancanOrderDetail));
	}

	@Override
	@Transactional
	public DiancanOrderDetailDTO create(DiancanOrderDetailDTO orderDTO) {
		String orderId = UUIDUtil.getTimeUUID(32);
		BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

		//        List<CartDTO> cartDTOList = new ArrayList<>();

		//1. 查询商品（数量, 价格）
		for (DiancanOrderDetail orderDetail : orderDTO.getOrderDetailList()) {
			DiancanProductInfo productInfo = productService.getById(orderDetail.getProductId());
			if (productInfo == null) {
				throw new ServiceException(ResultEnum.PRODUCT_NOT_EXIST.getMessage());
			}

			//2. 计算订单总价
			orderAmount = productInfo.getStoreSellPrice()
					.multiply(new BigDecimal(orderDetail.getProductQuantity()))
					.add(orderAmount);

			//订单详情入库
			orderDetail.setDetailId(UUIDUtil.getTimeUUID(32));
			orderDetail.setOrderId(orderId);
			BeanUtils.copyProperties(productInfo, orderDetail);
			baseMapper.insert(orderDetail);
			//            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity());
			//            cartDTOList.add(cartDTO);
		}


		//3. 写入订单数据库（orderMaster和orderDetail）
		DiancanOrderMaster orderMaster = new DiancanOrderMaster();
		orderDTO.setOrderId(orderId);
		BeanUtils.copyProperties(orderDTO, orderMaster);
		orderMaster.setOrderAmount(orderAmount);
		orderMaster.setOrderStatus(OrderStatusEnum.NEW_PAYED.getCode());
		orderMasterService.save(orderMaster);

		//4. 扣库存
		List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e ->
				new CartDTO(e.getProductId(), e.getProductQuantity())
		).collect(Collectors.toList());
		productService.decreaseStock(cartDTOList);

		//发送websocket消息
		webSocket.sendMessage(orderDTO.getOrderId());

		return orderDTO;
	}
}
